package oceanlife;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingWorker;

import oceanlife.pathfinding.Line2;
import oceanlife.pathfinding.Obstacles;
import oceanlife.pathfinding.Pillar;
import oceanlife.pathfinding.Pnt;
import oceanlife.pathfinding.SimpleGraphBuilder;


public class GenWorker extends SwingWorker<Integer, Integer>{
		private SimpleSimPanel simPanel;
		private FileWriter fstream = null;
		private PrintWriter posLogger = null;


		public GenWorker(SimpleSimPanel simPanel) {
			this.simPanel = simPanel;
			if(OLSet.getInt("PosLogging") == 1){
				try{
					fstream = new FileWriter("playbacklogs\\"+simPanel.getID(),true);
					posLogger = new PrintWriter(fstream,true);
				} catch (Exception e){
					e.printStackTrace();
				}
			}
		}

		protected Integer doInBackground() throws Exception
        {
			try {	
				CalcSimplePath(simPanel.getAgentGoals());
				for(int i = 0; i < simPanel.getScenarios(); i++){
					simPanel.setAgentScenario(i);
	                runLoop(i);
	                simPanel.finishCycle();
				}
				if(OLSet.getInt("PosLogging") == 1){
					posLogger.close();
				}
				//db.flushLogBuffer();
				//System.out.println("done");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return 0;
        }

		public void CalcSimplePath(ArrayList<Pnt> agentGoals){
    		try {
				SimpleGraphBuilder gB = new SimpleGraphBuilder(simPanel.getSimpleObs());
				simPanel.setSimpleGraphBuilder(gB);
				ArrayList<Line2> initLines = gB.createSimpleGraphLines();
				gB.makeGraph(initLines);
				for(Pnt goal : agentGoals){
					gB.addPoint(goal);
				}
				simPanel.updateGraph();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		
		public void runLoop(int scenario){
			try {
				ArrayList<Agent> agents = simPanel.getAgents();
				simPanel.addAgent();
				//testset interval genes
				if(OLSet.getInt("PosLogging") == 1){
					posLogger.println(RandomGen.getSeed()+" "+OLSet.get("testSet")+" "+OLSet.getInt("spawnInterval")+simPanel.getGenes().toString());
				}
				while(agents.size() > 0 && OLSet.getInt("stopping") == 0 && simPanel.getScenarioCycles() < OLSet.getInt("maxCycles")){
					while(OLSet.getInt("pauze") == 1 && OLSet.getInt("stopping") != 1){
						Thread.sleep(100);
					}
					if(simPanel.getScenarioCycles() % OLSet.getInt("spawnInterval") == OLSet.getInt("spawnInterval")-1){
						simPanel.addAgent();
					}
					java.util.Date javaDate = new java.util.Date();
				    long start = javaDate.getTime();
				    //Thread.sleep(100);
				    ArrayList<Integer> removeAgents = new ArrayList<Integer>();
				    //System.out.println(agents.size());
			    	if(OLSet.getInt("PosLogging") == 1){
			    		posLogger.println("Step");
			    	}
				    for(int i = 0; i < agents.size(); i++){
				    	Agent ag = agents.get(i);
				    	if(new Line2(ag.getPosition(),ag.getGoal()).length() < 1000.0){
				    		removeAgents.add(i);
				    	} else {
							ag.move(simPanel.getSimpleGraphBuilder());
							if(OLSet.getInt("PosLogging") == 1){
								posLogger.println(ag.getID().toString()+" "+ag.getPosition()+" "+ag.getGoal()+" "+ag.getFreeSpeed()+" "+ag.getDirection()+" "+ag.getColor().getRGB());
							}
				    	}
				    }
				    for(int i = removeAgents.size()-1; i >= 0; i--){
				    	simPanel.addAgentCycles(agents.get((int)removeAgents.get(i)).getCycles());
				    	agents.remove((int)removeAgents.get(i));
				    }
				    //if(agentsAfter != agents.size()){
				    //	System.out.println("should be: "+agentsAfter+" but is: "+agents.size());
				    //}
				    
				    javaDate = new java.util.Date();
				    long end = javaDate.getTime();
				    double cps = OLSet.getCps();
				    int tpc = (int) Math.round(1000/cps);
					//System.out.println((end-start)+" "+(tpc-(end-start))+" "+tpc+" "+(float)(end-start)/(float)tpc);
				    if(tpc > (end-start)){
				    	//Thread.sleep(tpc-(end-start));
				    }
				    
					simPanel.incrementCycles();
					simPanel.repaint();
					DecimalFormat procFormat = new DecimalFormat("00");
					//System.out.println("nodeset:"+simPanel.getSimpleGraphBuilder().getGraph().nodeSet().size());
				}
				//db.flushLogBuffer();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

        protected void done()
        {
                try
                {
                	//JOptionPane.showMessageDialog(f, get());
                }
                catch (Exception e)
                {
                        e.printStackTrace();
                }
        }


}